package com.jds.test.stringlength;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 多个handler
 * https://www.cnblogs.com/silyvin/articles/12056398.html
 * Created by sunyuming on 18/8/1.
 */
public class Server5 {
    public static void main(String[] args)  {

        //boss线程监听端口，worker线程负责数据读写
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        try{
            //辅助启动类
            ServerBootstrap bootstrap = new ServerBootstrap();
            //设置线程池
            bootstrap.group(boss,worker);

            //设置socket工厂
            bootstrap.channel(NioServerSocketChannel.class);

            ChannelHandler [] channelHandlers = {
                    new FixedLengthFrameDecoder(14),
                    new StringDecoder(),
                    new StringEncoder(),
                    new ServerHandler4(),
                    new ServerHandler5()
            };

            //设置管道工厂
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

                // 多个handler
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    //获取管道
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    //定长解码类
                    pipeline.addLast(channelHandlers[0]);
                    //字符串解码类
                    pipeline.addLast(channelHandlers[1]);

                    pipeline.addLast(channelHandlers[2]);
                    //处理类
                    pipeline.addLast(channelHandlers[3]);
                    pipeline.addLast(channelHandlers[4]);

                }
            });

            //绑定端口
            ChannelFuture future = bootstrap.bind(8866).sync();
            System.out.println("server start ...... ");

            //等待服务端监听端口关闭
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //优雅退出，释放线程池资源
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
